<template>
  <div class="account-settings-info-view">
    <a-row :gutter="16">
      <a-col :md="24" :lg="16">
        <a-spin :spinning="confirmLoading">
          <a-form :form="form" layout="vertical">
            <a-form-item
              label="用户名称"
            >
              <a-input placeholder="请输入用户名称" v-decorator="[ 'realname', {}]"/>
            </a-form-item>


            <a-form-item label="头像" >
              <j-image-upload class="avatar-uploader" text="上传" @change="handleChange" v-model="fileList" :disabled="disableSubmit"></j-image-upload>
            </a-form-item>

            <a-form-item label="生日" >
              <a-date-picker
                style="width: 100%"
                placeholder="请选择生日"
                v-decorator="['birthday', {initialValue:!model.birthday?null:moment(model.birthday,dateFormat)}]" :disabled="disableSubmit"
                :getCalendarContainer="node => node.parentNode"/>
            </a-form-item>

            <a-form-item label="性别" >
              <j-dict-select-tag v-decorator="['sex', {}]" title="性别" dictCode="sex" placeholder="请选择性别" :triggerChange="true" :disabled="disableSubmit"/>
            </a-form-item>

            <a-form-item label="邮箱" >
              <a-input placeholder="请输入邮箱" v-decorator="[ 'email', validatorRules.email]" :disabled="disableSubmit"/>
            </a-form-item>

            <a-form-item label="手机号码">
              <a-input placeholder="请输入手机号码" :disabled="isDisabledAuth('user:form:phone') || disableSubmit" v-decorator="[ 'phone', validatorRules.phone]"/>
            </a-form-item>

            <a-form-item label="座机" >
              <a-input placeholder="请输入座机" v-decorator="[ 'telephone', validatorRules.telephone]" :disabled="disableSubmit"/>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit" :disabled="confirmLoading">保存</a-button>
            </a-form-item>
          </a-form>
        </a-spin>
      </a-col>

    </a-row>

  </div>
</template>

<script>
  import pick from 'lodash.pick'
  import { getCurrLoginUserInfo, changeSysUserInfo } from '@api/api'
  import { disabledAuthFilter } from "@/utils/authFilter"
  import moment from 'moment'
  import {duplicateCheck } from '@/api/api'

  export default {
    components: {

    },
    data () {
      return {
        confirmLoading: false,
        form: this.$form.createForm(this),
        picUrl: "",
        uploadLoading:false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        dateFormat:"YYYY-MM-DD",
        fileList:[],
        disableSubmit:false,
        validatorRules: {
          phone:{rules: [{validator: this.validatePhone}]},
          email: {
            rules: [{
              validator: this.validateEmail
            }],
          },
          telephone: {
            rules: [
              { pattern: /^0\d{2,3}-[1-9]\d{6,7}$/, message: '请输入正确的座机号码' },
            ]
          }
        }
      }
    },
    created() {
      this.showData();
    },
    methods: {
      moment,
      isDisabledAuth(code){
        return disabledAuthFilter(code);
      },
      showData () {
        this.form.resetFields();
        getCurrLoginUserInfo({id: 1}).then((res) => {

          if (res.success) {
            this.model = Object.assign({}, res.result)
          } else {
            this.$message.warn(res.message);
          }
        }).then(() => {
            this.fileList = this.model.avatar;
          setTimeout(() => {
            this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.model,
                'id','realname','birthday','sex','email','phone','telephone'
              ));
            });
          }, 1000)
          this.fileList = JSON.parse(JSON.stringify(this.fileList))
        });
      },
      handleSubmit(){
        this.form.validateFields((err, values) => {
          if (!err) {
            this.confirmLoading = true;
            let formData = Object.assign(this.model, values)
            formData.avatar = JSON.stringify(this.fileList);
            changeSysUserInfo(formData).then((res)=>{
              if(res.success){
                this.$message.success(res.message);
              }else{
                this.$message.warning(res.message);
              }
            }).finally(() => {
              this.confirmLoading = false;
              this.showData();
            });
          }
        });
      },
      handleChange (info) {
        this.fileList = info;
      },
      validateEmail(rule, value, callback){
        if(!value){
          callback()
        }else{
          if(new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)){
            var params = {
              tableName: 'sys_user',
              fieldName: 'email',
              fieldVal: value,
              dataId: this.model.id
            };
            duplicateCheck(params).then((res) => {
              console.log(res)
              if (res.success) {
                callback()
              } else {
                callback("邮箱已存在!")
              }
            })
          }else{
            callback("请输入正确格式的邮箱!")
          }
        }
      }
    },
    validatePhone(rule, value, callback){
      if(!value){
        callback()
      }else{
        //update-begin--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
        if(new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)){
          //update-end--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
          callback()
          var params = {
            tableName: 'sys_user',
            fieldName: 'phone',
            fieldVal: value,
            dataId: this.model.id
          };
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback("手机号已存在!")
            }
          })
        }else{
          callback("请输入正确格式的手机号码!");
        }
      }
    }
  }
</script>

<style lang="less" scoped>

</style>